package com.liaozibo.swagger.demo.config;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RequestMethod;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseMessageBuilder;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.Arrays;
import java.util.Collections;

/**
 * author: liaozibo
 * createTime: 2021/3/14 22:43
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 配置 Swagger2
     * http://localhost:8080/v2/api-docs
     * */
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
//                .apis(RequestHandlerSelectors.any()) // 扫描所有
//                .paths(PathSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.liaozibo.swagger.demo.controller")) // 扫描指定包下的接口
                .paths(Predicates.or(PathSelectors.ant("/users"), PathSelectors.ant("/users/*"))) // 扫描指定 URL 下的接口
                .build()
                .apiInfo(apiInfo())
                .useDefaultResponseMessages(false) // 不使用默认响应消息
                .globalResponseMessage(RequestMethod.GET, Arrays.asList( // 自定义全局响应消息
                        new ResponseMessageBuilder()
                                .code(500)
                                .message("服务器发生异常")
                                .responseModel(new ModelRef("Error"))
                                .build(),
                        new ResponseMessageBuilder()
                                .code(403)
                                .message("资源不可用")
                                .build()
                ));
    }

    /**
     * 配置文档信息
     * */
    private ApiInfo apiInfo() {
    /* Params:
        title – title
        description – description
        version – version
        termsOfServiceUrl – termsOfServiceUrl
        contact – contact
        license – license
        licenseUrl – license url
        vendorExtensions – vendor extensions */
        return new ApiInfo(
                "SpringBoot 集成 Swagger2 示例",
                "示例参考：https://developer.ibm.com/zh/articles/j-using-swagger-in-a-spring-boot-project/",
                "API v1.0",
                "Term of service",
                new Contact("liaozibo", "liaozibo.com", "liaozibo@qq.com"),
                "MIT", "https://opensource.org/licenses/MIT", Collections.emptyList());
    }
}
